import requests

import pandas as pd


def get_financial_data(stock_code: str) -> pd.DataFrame:
    response = requests.get(
        "http://www.cninfo.com.cn/data20/financialData/getMainIndicators?scode=%s&sign=1" % stock_code
    ).json()
    record = response["data"]["records"][0]

    data = record["year"] + record["one"] + record["three"] + record["middle"]
    data = sorted(data, key=lambda x: x["ENDDATE"], reverse=True)

    mapping = {
        'ENDDATE': '时间',
        'F004N': '基本每股收益(元)',
        'F008N': '每股净资产(元)',
        'F010N': '每股资本公积金(元)',
        'F067N': '加权净资产收益率(%)',
        'F042N': '流动比率',
        'F043N': '速动比率',
        'F041N': '资产负债比率(%)',
        'F022N': '应收账款周转率(次)',
        'F023N': '存货周转率(次)',
        'F029N': '流动资产周转率(次)',
        'F026N': '固定资产周转率(次)',
        'F025N': '总资产周转率(次)',
        'F011N': '营业利润率(%)',
        'F017N': '净利润率(%)',
        'F078N': '毛利率(%)',
        'F016N': '总资产报酬率(%)',
        'F052N': '营业收入增长率(%)',
        'F056N': '总资产增长率(%)',
        'F058N': '营业利润增长率(%)',
        'F053N': '净利润增长率(%)',
        'F054N': '净资产增长率(%)'
    }
    df = pd.DataFrame(data)
    df = df.rename(columns=mapping)
    df = df.reindex(columns=mapping.values())
    df = df.ffill()

    return df


if __name__ == '__main__':
    print(get_financial_data("688516"))
